#include <cserver/session/console.h>
#include <boost/asio.hpp>
#include <cserver/context.h>
namespace csrv{

	Console::Console(Context& ctx) : context(ctx){}
	void Console::start(){
		boost::asio::spawn(context.ios_aserver, [&](boost::asio::yield_context yield) { do_console_(yield);});
	}
	void Console::do_console_(boost::asio::yield_context yield){
		namespace posix = boost::asio::posix;
		posix::stream_descriptor input_(context.ios_aserver, ::dup(STDIN_FILENO));
		posix::stream_descriptor output_(context.ios_aserver, ::dup(STDOUT_FILENO));
		boost::asio::streambuf input_buffer_(1024);

		boost::system::error_code ec;
		for(;;){
			auto n = boost::asio::async_read_until(input_, input_buffer_, '\n', yield[ec]);
			std::vector<char> buf(n);
			input_buffer_.sgetn(&buf[0], n);
			buf.back() = 0;

			std::stringstream sstr(&buf[0]);
			std::string text;
			while(sstr >> text){
				if (text == "quit"){
					context.stop();
					return;
				}
			}
		}
	}

}

